package com.example.demo.angio.medicine;

import com.alibaba.fastjson.JSON;
import com.example.demo.angio.common.Result;
import com.example.demo.angio.common.Utils;
import com.example.demo.angio.login.LoginDto;
import com.example.demo.angio.login.LoginService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.CharArrayWriter;
import java.io.IOException;
import java.io.Reader;
import java.util.List;

@WebServlet(name = "MedAPI", value = "/MedAPI")
public class MedAPI extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {

        MedService medService=new MedService();

        //得到药物列表
        List<Medicine> medList=medService.getMedList();

        Utils.outResult(resp, Result.success(medList));
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        try {
            req.setCharacterEncoding("UTF-8");

            //读取用户输入
            Reader reader = req.getReader();
            CharArrayWriter out = new CharArrayWriter();
            boolean ok = false;
            try
            {
               //将用户输入存入缓存，转化为Json后进入Dto
                char[] charBuff = new char[1024];
                int len = -1;

                while ((len = reader.read(charBuff)) != -1)
                {
                    out.write(charBuff, 0, len);
                }

                String json = out.toString();

                MedDto dto = JSON.parseObject(json, MedDto.class);

                //判断用户查询是否成功
                ok = new MedService().checkMedicine(dto);

            } finally
            {
                out.flush();
                out.close();
            }

            if (ok)
            {
                //若查询成功，用doGet方法输出被查询的药物
                doGet(req,resp);
                Utils.outResult(resp, Result.success());
            }
            else
            {
                Utils.outResult(resp, Result.fail(Result.ERR_CODE_BUSINESS, "对不起，无对应药品信息"));
            }
        } catch (Exception e)
        {
            Utils.outResult(resp, Result.fail(Result.ERR_CODE_SYS, "系统升级中。"));
        }
    }
    }

